package jcrosswords.ui;

import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

import jcrosswords.domain.Board;
import jcrosswords.domain.Coordinates;

public class BoardPanel extends JPanel {

	private static final long serialVersionUID = 1L;
	
	private Board board;
	private CellPanel[][] cellPanels;
	private JFrame f = new JFrame();
	
	public BoardPanel(Board board) {
		setBoard(board);
		cellPanels = new CellPanel[board.getWidth()][board.getHeight()];
		for (int y = 0; y < board.getHeight(); y++) {
			for (int x = 0; x < board.getWidth(); x++) {
				CellPanel c = new CellPanel(board.getCell(new Coordinates(x, y)));
				c.setBorder(new LineBorder(Color.BLACK));
				cellPanels[x][y] = c;
			}
		}
		init();
		popUp();
	}

	public Board getBoard() {
		return board;
	}

	public void setBoard(Board board) {
		if(board == null) {
			throw new IllegalArgumentException();
		}
		this.board = board;
	}
	
	public void refresh() {
		for (int y = 0; y < board.getHeight(); y++) {
			for (int x = 0; x < board.getWidth(); x++) {
				cellPanels[x][y].refresh();
			}
		}
		f.repaint();
	}
	
	private void init() {
		setLayout(new GridLayout(board.getHeight(), board.getWidth()));
		
		for (int y = 0; y < board.getHeight(); y++) {
			for (int x = 0; x < board.getWidth(); x++) {
				cellPanels[x][y].setCell(board.getCell(new Coordinates(x, y)));
				add(cellPanels[x][y]);
			}
		}
	}
	
	private void popUp() {
		f.add(this);
		f.setSize(1024, 768);
		f.setVisible(true);
	}
	
}